import { defineStore } from 'pinia';
import eventBus, { Events } from '@/event-bus';
import type { Tool } from '@/types';
import config from '@/config';

// 定义工具存储
export const useToolsStore = defineStore('tools', {
    state: () => ({
        tools: config.tools as Tool[],
        activeToolKey: config.tools[0]?.key || ''
    }),

    getters: {
        /**
         * 获取当前激活的工具
         */
        activeTool(state): Tool | undefined {
            return state.tools.find(tool => tool.key === state.activeToolKey);
        }
    },

    actions: {
        /**
         * 设置激活的工具
         * @param key 工具的key
         */
        setActiveTool(key: string): void {
            const toolExists = this.tools.some(tool => tool.key === key);
            if (toolExists) {
                this.activeToolKey = key;
                eventBus.emit(Events.TOOL_CHANGED, key);
            }
        },

        /**
         * 添加自定义工具
         * @param tool 新工具
         */
        addTool(tool: Tool): void {
            if (!this.tools.some(t => t.key === tool.key)) {
                this.tools.push(tool);
            }
        }
    }
});
